//
// Created by xili on 2024/9/18 18:52.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    int minOperations(vector<int> &nums, int x) {
        int sum = accumulate(nums.begin(), nums.end(), 0);
        if (sum < x) {
            return -1;
        }
        int n = nums.size();
        int ans = n + 1;
        int l = -1, r = 0;
        int ls = 0, rs = sum;

        for (; l < n; l++) {
            if (l != -1) {
                ls += nums[l];
            }
            while (r < n && ls + rs > x) {
                rs -= nums[r];
                r++;
            }
            if (ls + rs == x) {
                ans = min(ans, (l + 1) + (n - r));
            }
        }
        return ans > n ? -1 : ans;
    }
};